#!/bin/bash
# ==========================================
# 🧪 Flutter iOS Development 自动打包脚本
# 说明：使用开发证书导出测试包（本地调试 / 真机安装）
# ==========================================
set -euo pipefail

cd "$(dirname "$0")"

APP_NAME="Runner"
CONFIGURATION="Debug"
EXPORT_METHOD="development"
OUTPUT_DIR="build/ios/dev-ipa"
PROJECT_PATH="$(pwd)/ios/Runner.xcworkspace"

DATE_STR=$(date +"%y-%m-%d-%H-%M")
IPA_NAME="casdonn_dev_${DATE_STR}.ipa"

echo "🧹 Step 1: Flutter clean + pub get"
flutter clean
flutter pub get

echo "📦 Step 2: CocoaPods install"
cd ios
pod install --repo-update
cd ..

echo "🏗 Step 3: Flutter build ios --debug --no-codesign"
flutter build ios --debug --no-codesign

ARCHIVE_PATH="build/ios/archive/$APP_NAME-dev.xcarchive"
echo "📦 Step 4: Xcode Archive (Development)"
xcodebuild -workspace "$PROJECT_PATH" \
           -scheme "$APP_NAME" \
           -configuration "$CONFIGURATION" \
           -archivePath "$ARCHIVE_PATH" \
           -destination "generic/platform=iOS" \
           -allowProvisioningUpdates \
           clean archive

mkdir -p "$OUTPUT_DIR"
EXPORT_OPTIONS_PLIST="$OUTPUT_DIR/ExportOptions_dev.plist"
cat > "$EXPORT_OPTIONS_PLIST" <<EOL
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
  <key>method</key>
  <string>$EXPORT_METHOD</string>
  <key>signingStyle</key>
  <string>automatic</string>
  <key>destination</key>
  <string>export</string>
  <key>compileBitcode</key>
  <false/>
  <key>stripSwiftSymbols</key>
  <true/>
  <key>manageAppVersionAndBuildNumber</key>
  <false/>
</dict>
</plist>
EOL

echo "📤 Step 5: Export Development IPA"
xcodebuild -exportArchive \
           -archivePath "$ARCHIVE_PATH" \
           -exportOptionsPlist "$EXPORT_OPTIONS_PLIST" \
           -exportPath "$OUTPUT_DIR" \
           -allowProvisioningUpdates

IPA_PATH=$(find "$OUTPUT_DIR" -type f -name "*.ipa" | head -n 1)
if [ -f "$IPA_PATH" ]; then
  mv "$IPA_PATH" "$OUTPUT_DIR/$IPA_NAME"
  echo "✅ Development IPA 已生成：$OUTPUT_DIR/$IPA_NAME"
  open "$OUTPUT_DIR"
else
  echo "❌ 未找到 Development IPA 文件，请检查导出步骤。"
fi

echo ""
echo "🎉 Development 打包完成。按任意键退出。"
read -n 1
